package level02;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 一、项目需求：请用户完成一个 UDP 接收端作为模拟网络聊天室的操作。
 * 1: 创建 UDP 传输下的聊天室发送端 UDPSend 类
 * 2: 创建 UDP 传输下的聊天室接收端 Room 类
 */
public class UDPSend {
    public static void main(String[] args) {
        //创建两个个线程池，用来管理发送和接收线程
        ExecutorService executor1 = Executors.newSingleThreadExecutor();
        ExecutorService executor2 = Executors.newSingleThreadExecutor();
        //发送线程
        executor1.submit(() -> {
            try {
                //创建一个套接字，用来向接收端发送信息
                DatagramSocket socket = new DatagramSocket();
                byte[] bytes = new byte[1024];
                //创建一个UDP报文，用作封装发送的信息
                DatagramPacket packet = new DatagramPacket(bytes,
                        bytes.length,
                        InetAddress.getLocalHost(),
                        8888);
                //死循环发送信息给接收端
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String nextLine = scanner.nextLine();
                    //将数据设置到UDP报文中
                    packet.setData(nextLine.getBytes(StandardCharsets.UTF_8));
                    packet.setLength(nextLine.getBytes(StandardCharsets.UTF_8).length);
                    //将UDP报文发送给接收端
                    socket.send(packet);
                }
            } catch (SocketException | UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        //接收线程
        executor2.submit(() -> {
            try {
                //创建一个套接字,接收来自发送端的信息
                DatagramSocket socket = new DatagramSocket(6666);
                //创建一个UDP报文，接收UDP报文
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
                //死循环接收来自发送端的响应信息
                while (true) {
                    socket.receive(packet);
                    String message = new String(packet.getData(), 0, packet.getLength());
                    System.out.println("来自接收端" + packet.getAddress().getHostAddress() + "的响应信息为:" + message);
                    if (message.equals("bye")) {
                        break;
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });


    }
}
